#include <iostream>
#include <vector>
#include <algorithm>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

pthread_mutex_t mutex;
pthread_cond_t cond_produce;
pthread_cond_t cond_consume;

#define SIZE 10
int source[SIZE];
int count = 0;

void* Produced(void* args)
{
    for (int i = 0; i < 20; i++)
    {
        pthread_mutex_lock(&mutex); // 加锁

        while (count == SIZE) // 共享资源已满
        {
            pthread_cond_wait(&cond_produce, &mutex);
        }

        source[count++] = i;
        printf("Produced: %d\n", i);
        pthread_cond_signal(&cond_consume);

        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    return NULL;
}

void* Consumed(void* args)
{
    for (int i = 0; i < 20; i++)
    {
        pthread_mutex_lock(&mutex);

        while (count == 0)
        {
            pthread_cond_wait(&cond_consume, &mutex);
        }

        int item = source[--count];
        printf("Consumed: %d\n", item);

        pthread_cond_signal(&cond_produce);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    return NULL;
}

int main()
{
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond_produce, NULL);
    pthread_cond_init(&cond_consume, NULL);

    pthread_t producer, consumer;
    pthread_create(&producer, NULL, Produced, NULL);
    pthread_create(&consumer, NULL, Consumed, NULL);

    pthread_join(producer, NULL);
    pthread_join(consumer, NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond_produce);
    pthread_cond_destroy(&cond_consume);

    return 0;
}


// #define NUM_SIZE 100
// #define THREAD_COUNT 4

// std::vector<int> nums(NUM_SIZE);

// void* section_sort(void* argv)
// {
//     int start = *(int*)argv;
//     int end = start + NUM_SIZE / THREAD_COUNT;

//     sort(nums.begin()+start, nums.begin()+end);

//     return nullptr;
// }

// int main()
// {
//     pthread_t threads[THREAD_COUNT];

//     srand(time(NULL));
//     for (int i = 0; i < NUM_SIZE; i++)
//     {
//         nums[i] = rand() % 1000;
//     }

//     for (int i = 0; i < THREAD_COUNT; i++)
//     {
//         int* pos = new int;
//         *pos = i * (NUM_SIZE / THREAD_COUNT); // 划分区域

//         pthread_create(&threads[i], nullptr, section_sort, pos);
//     }

//     for (int i = 0; i < THREAD_COUNT; i++)
//     {
//         pthread_join(threads[i], nullptr);
//     }

//     int block = NUM_SIZE / THREAD_COUNT;
//     for (int i = 0; i < THREAD_COUNT; i++)
//     {
//         int start = i * block;
//         for (int j = 0; j < block; j++)
//         {
//             std::cout << nums[start+j] << std::endl;
//         }
//         std::cout << std::endl;
//     }

//     return 0;
// }
